package play

import (
	"encoding/json"
	"fmt"
	"github.com/faiface/beep"
	"github.com/faiface/beep/mp3"
	"github.com/faiface/beep/speaker"
	"log"
	"music/api"
	"music/prompt"
	"music/utils"
	"os"
	"strconv"
	"time"
)

var (
	detailResult api.DetailResult
)

type MusicEntry struct {
	Libs       []api.Song
	NowInx     int
	Name       string
	Author     string
	Source     string   //位置
	FileStream *os.File // 文件流
}

func (m *MusicEntry) Open() {

	detail, err := api.MusicDetail(strconv.Itoa(m.Libs[m.NowInx].Id))
	if err != nil {
		log.Fatal("获取音乐错误")
	}

	err = json.Unmarshal([]byte(detail), &detailResult)
	if err != nil {
		log.Fatalln(err.Error())
	}

	if detailResult.Data.Url == "" {
		//goto InputNo
	}

	path, err := utils.Download(detailResult.Data.Url)
	if err != nil {
		log.Fatalln(err.Error())
	}

	m.Source = path

	author := ""
	for _, val := range m.Libs[m.NowInx].Artists {
		author += val.Name + " "
	}
	m.Author = author
	m.Name = m.Libs[m.NowInx].Name

	m.FileStream, err = os.Open(m.Source)
	if err != nil {
		log.Fatal(err)
	}
}

func (m *MusicEntry) Play(done chan bool, ctrl **beep.Ctrl) {
	streamer, format, err := mp3.Decode(m.FileStream)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		fmt.Println("play func defer")
		_ = streamer.Close()
	}()

	err = speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
	if err != nil {
		log.Fatal(err)
	}

	prompt.Playing(m.Name + "-" + m.Author)

	*ctrl = &beep.Ctrl{Streamer: beep.Seq(streamer, beep.Callback(func() {
		done <- true
	})), Paused: false}
	speaker.Play(*ctrl)

	if <-done {
		if (m.NowInx + 1) < len(m.Libs) {
			m.NowInx = m.NowInx + 1
			m.Open()
			m.Play(done, ctrl)
		} else {
			fmt.Println("已经全部播放完毕")
		}
	}
}
